<template>
    <div>
        <div class="upload-item"
             v-for="(item,index) in uploadImgs"
             :key="index">
            <img :src="item.url"
                 :preview="preview"
                 alt="">
            <span v-if="!imgList"
                  @click="removeImg(item.name,index)"></span>
        </div>
        <div class="upload-item"
             v-if="!imgList">
            <img src="@static/images/upload.png"
                 alt="">
            <input type="file"
                   :name="('file'+uploadIndex)"
                   @change="upload">
        </div>
    </div>
</template>
<script>
export default {
    name: 'upload',
    data () {
        return {
            preview: '', // 预览图片分组
            uploadImgs: [], // 图片上传回传的照片
            uploadImgFormData: null, // 图片上传formData对象
            uploadIndex: 0,
            images: []
        }
    },
    props: {
        imgList: {
            default: ''
        }
    },
    created () {
        this.preview = new Date().getTime()
        if (this.imgList) {
            this.imgList.forEach(item => {
                this.uploadImgs.push({
                    url: item
                })
            })
        }
    },
    methods: {
        upload (e) {
            let This = this
            let file = e.target.files[0]
            if (this.uploadImgFormData) {
                this.uploadImgFormData.append(e.target.name, file)
            } else {
                let formData = new FormData()
                formData.append(e.target.name, file)
                this.uploadImgFormData = formData
            }
            if (file.type.indexOf('image') == 0) {
                let reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onload = function (e) {
                    This.uploadImgs.unshift({
                        url: e.target.result,
                        name: `file${This.uploadIndex}`
                    })
                    This.images.unshift(file)
                    This.$emit('setFormData', This.uploadImgFormData, This.uploadImgs.length, This.uploadImgs,This.images)
                    This.$nextTick(() => {
                        This.$previewRefresh()
                    })
                }
            }
            this.uploadIndex++
        },
        removeImg (name, index) {
            this.uploadImgs.splice(index, 1)
            this.images.splice(index, 1)
            this.uploadImgFormData.delete(name)
            this.$emit('setFormData', this.uploadImgFormData, this.uploadImgs.length,This.uploadImgs,This.images)
        }
    }
}
</script>
<style scoped>
	.upload-wrap{
		margin-top:-10px;
	}
	.upload-wrap img{
		width:43px;
		height: 43px;
		border-radius: 5px;
	}
	.upload-wrap>div>div:nth-child(5n+5){
		margin-right: 15px!important;
	}
</style>
